package com.oauth.twitter.client.ui;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.oauth.components.client.beans.OAuthUrl;
import com.oauth.components.client.rpc.OAuthAsnyCallBack;
import com.oauth.twitter.client.rpc.TwitterRemoteServiceAsync;

public class LoginPanel extends Composite {

	private static LoginPanelUiBinder uiBinder = GWT
			.create(LoginPanelUiBinder.class);
	TwitterRemoteServiceAsync mService;

	interface LoginPanelUiBinder extends UiBinder<Widget, LoginPanel> {
	}

	@UiField
	HorizontalPanel hPanel;

	@UiField
	Button signIn;

	public LoginPanel() {
		initWidget(uiBinder.createAndBindUi(this));
		hPanel.setCellHorizontalAlignment(signIn, VerticalPanel.ALIGN_CENTER);
	}

	public void setService(TwitterRemoteServiceAsync pService) {
		mService = pService;
	}

	@UiHandler("signIn")
	public void onClick(ClickEvent pEvent) {
		signIn.setEnabled(false);

		mService.getSignInUrl(new OAuthAsnyCallBack<OAuthUrl>() {

			@Override
			public void onSuccess(OAuthUrl pResult) {
				if (pResult.getOAuthUrl().startsWith("http")) {
					Window.Location.assign(pResult.getOAuthUrl());
				} else {
					Window.Location.assign(Window.Location.getPath() + pResult);
				}
			}

		});
	}

}
